<template>
  <div class="user-profile-container">
    <a-row :gutter="24">
      <!-- 左侧个人信息卡片 -->
      <a-col :xs="24" :lg="8">
        <a-card title="个人信息" :bordered="false" class="profile-card">
          <div class="profile-info">
            <div class="avatar-section">
              <a-avatar :size="80" :src="userStore.loginUser?.userAvatar" class="profile-avatar">
                {{
                  userStore.loginUser?.userName?.charAt(0) ||
                  userStore.loginUser?.userAccount?.charAt(0)
                }}
              </a-avatar>
              <div class="avatar-info">
                <h3>{{ userStore.loginUser?.userName || userStore.loginUser?.userAccount }}</h3>
                <a-tag :color="userStore.loginUser?.userRole === 'admin' ? 'red' : 'blue'">
                  {{ userStore.loginUser?.userRole === 'admin' ? '管理员' : '普通用户' }}
                </a-tag>
              </div>
            </div>

            <a-divider />

            <div class="info-items">
              <div class="info-item">
                <span class="label">账号：</span>
                <span>{{ userStore.loginUser?.userAccount }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱：</span>
                <span>{{ userStore.loginUser?.userEmail || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机：</span>
                <span>{{ userStore.loginUser?.userPhone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">生日：</span>
                <span>{{ formatDate(userStore.loginUser?.birthday) || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">注册时间：</span>
                <span>{{ formatDate(userStore.loginUser?.createTime) }}</span>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 右侧编辑表单 -->
      <a-col :xs="24" :lg="16">
        <a-card title="编辑资料" :bordered="false" class="edit-card">
          <a-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            layout="vertical"
            @finish="handleSubmit"
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="用户昵称" name="userName">
                  <a-input v-model:value="formData.userName" placeholder="请输入用户昵称" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="生日" name="birthday">
                  <a-date-picker
                    v-model:value="formData.birthday"
                    placeholder="请选择生日"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="邮箱" name="userEmail">
                  <a-input v-model:value="formData.userEmail" placeholder="请输入邮箱" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号" name="userPhone">
                  <a-input v-model:value="formData.userPhone" placeholder="请输入手机号" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item label="头像URL" name="userAvatar">
              <a-input v-model:value="formData.userAvatar" placeholder="请输入头像URL" />
            </a-form-item>

            <a-form-item label="个人简介" name="userProfile">
              <a-textarea
                v-model:value="formData.userProfile"
                placeholder="请输入个人简介"
                :rows="4"
              />
            </a-form-item>

            <a-form-item>
              <a-space>
                <a-button type="primary" html-type="submit" :loading="loading" size="large">
                  保存修改
                </a-button>
                <a-button size="large" @click="handleReset"> 重置 </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import dayjs, { type Dayjs } from 'dayjs'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api/user'
import type { UserEditRequest } from '@/types/user'

const userStore = useUserStore()
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<{
  userName: string
  userEmail: string
  userPhone: string
  userAvatar: string
  userProfile: string
  birthday: Dayjs | null
}>({
  userName: '',
  userEmail: '',
  userPhone: '',
  userAvatar: '',
  userProfile: '',
  birthday: null,
})

// 表单验证规则
const formRules = {
  userName: [{ max: 50, message: '昵称长度不能超过50位', trigger: 'blur' }],
  userEmail: [{ type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }],
  userPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }],
  userProfile: [{ max: 500, message: '简介长度不能超过500位', trigger: 'blur' }],
}

// 初始化表单数据
const initFormData = () => {
  if (userStore.loginUser) {
    formData.userName = userStore.loginUser.userName || ''
    formData.userEmail = userStore.loginUser.userEmail || ''
    formData.userPhone = userStore.loginUser.userPhone || ''
    formData.userAvatar = userStore.loginUser.userAvatar || ''
    formData.userProfile = userStore.loginUser.userProfile || ''
    // 处理 LocalDate 格式的生日 (YYYY-MM-DD)
    formData.birthday = userStore.loginUser.birthday
      ? dayjs(userStore.loginUser.birthday, 'YYYY-MM-DD')
      : null
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    loading.value = true

    const editData: UserEditRequest = {
      id: userStore.loginUser?.id,
      userAccount: userStore.loginUser?.userAccount,
      userName: formData.userName,
      userPhone: formData.userPhone,
      userAvatar: formData.userAvatar,
      userProfile: formData.userProfile,
      userEmail: formData.userEmail,
      birthday: formData.birthday ? formData.birthday.format('YYYY-MM-DD') : undefined,
    }

    await userApi.editUser(editData)
    message.success('保存成功')

    // 重新获取用户信息
    await userStore.fetchLoginUser()
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 处理重置
const handleReset = () => {
  initFormData()
  formRef.value?.resetFields()
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY-MM-DD')
}

// 组件挂载时初始化数据
onMounted(() => {
  if (!userStore.loginUser) {
    userStore.fetchLoginUser().then(() => {
      initFormData()
    })
  } else {
    initFormData()
  }
})
</script>

<style scoped>
.user-profile-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card,
.edit-card {
  height: fit-content;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 20px;
}

.profile-avatar {
  display: block;
  margin: 0 auto 16px;
}

.avatar-info h3 {
  margin: 0 0 8px;
  font-size: 18px;
  font-weight: 600;
}

.info-items {
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

@media (max-width: 768px) {
  .user-profile-container {
    padding: 16px;
  }
}
</style>
